import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserService } from '../user/user.service';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
  ) {}

  async validateUser(email: string, password: string): Promise<any> {
    const u = await this.userService.findUserEmail(email);
    if (u && u.password === password) {
      const { password: _password, ...result } = u;
      return result;
    }
    return null;
  }

  async jwtSign(userId: string) {
    const u = await this.userService.findOne(+userId);
    if (!u) {
      throw new UnauthorizedException('用户名密码不正确');
    }
    const token = this.jwtService.sign({ email: u.email, id: u.id });
    return {
      token,
    };
  }
}
